<template>
  <div>

    <el-button type="primary" v-has="'btn.Coupon.rule'">编辑</el-button>
    <el-button type="success" v-has="'btn.Coupon.update'">删除</el-button>
     <el-button type="info">成功</el-button>



     
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div>
        <!-- v-model="input" -->
        <el-input
          placeholder="用户名"
          style="width: 180px"
          size="small"
          v-model="keyword"
        ></el-input>
        <el-button
          type="primary"
          size="small"
          style="margin-left: 20px"
          icon="el-icon-search"
          @click="searchUser"
          >查询</el-button
        >
        <el-button size="small" @click="clear">清空</el-button>
      </div>
      <!-- 按钮 -->
      <div style="margin-top: 30px">
        <el-button type="primary" size="small" @click="showDialog"
          >添加</el-button
        >
        <el-button type="danger"   :disabled="idList.length <=0 " size="small" @click="removeAllUser">批量删除</el-button>
      </div>
      <!-- 表格 -->
      <!-- :data="tableData" -->
      <el-table
      v-loading="loading"
        :data="pageList"
        stripe
        border
        @selection-change="handleSelectionChange"
        style="width: 100%; margin-top: 30px"
      >
        <el-table-column     type="selection" width="55"> </el-table-column>
        <el-table-column type="index" align="center" label="序号" width="80">
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150">
        </el-table-column>
        <el-table-column prop="nickName" label="用户昵称" width="150">
        </el-table-column>
        <el-table-column prop="roleName" label="角色列表"> </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间"> </el-table-column>
        <el-table-column prop="gmtModified" label="更新时间"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              type="info"
              size="small"
              title="分配角色"
              @click="showDispatchRole(row)"
              icon="el-icon-s-custom"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              title="编辑用户"
              @click="showEditDialog(row)"
              icon="el-icon-edit-outline"
            ></el-button>
            <!-- <el-button
              type="danger"
              size="small"
             
            ></el-button> -->
            <el-popconfirm
                @onConfirm="removeOneUser(row)"
                :title="`你确定删除${row.username}`"
                style="margin-left: 10px;"
              >
                <el-button type="danger" slot="reference" size="small"  title="删除用户"  icon="el-icon-delete"></el-button>
              </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="getPageList"
        style="margin-top: 30px"
        :current-page="current"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageSize"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加修改消息盒子 -->
    <el-dialog :title="userControl.id ? '修改用户':'添加用户'" :visible.sync="dialogFormVisible" top="0">
      <el-form
        ref="userControlForm"
        :model="userControl"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userControl.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称"  >
          <el-input
            v-model="userControl.nickName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userControl.id">
          <el-input
            v-model="userControl.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserControl">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的消息盒子 -->
    <el-dialog title="设置角色" :visible.sync="roleVisible">
  <el-form label-width="70px">
    <el-form-item label="用户名" >
      <el-input disabled  v-model="username" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="角色列表" >
      <!-- checkbox 复选框的成组使用数组的集合  单个使用绑定的是checked操作的是布尔值 -->
      <el-checkbox :indeterminate="isIndeterminate"  v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
  <div style="margin: 15px 0;"></div>
  <el-checkbox-group  v-model="checkAllRoles" @change="handleCheckedRolesChange">
    <el-checkbox  v-for="(role,index) in rolesList" :key="role.id" :label="role.id" >{{role.roleName}}</el-checkbox>
  </el-checkbox-group>
    </el-form-item>
  </el-form>
  <div slot="footer" >
    <el-button @click="roleVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRoles">确 定</el-button>
  </div>
</el-dialog>

  </div>
</template>
<script>
import { Message } from "element-ui";
import { mapGetters } from "vuex";
export default {
  name: "Management",
  data() {
    return {
      checkAll: false,
      roles:[],
      checkAllRoles:[],
      isIndeterminate: true,
      current: 1,
      pageSize: 5,
      dialogFormVisible: false,
      // 获取分页数据参数
      userControl: {
        username: '',
        nickName: '',
        password: ''
      },
      // 校验规则
      rules: {
        username: [
          { required: true, message: "用户名必须填写", trigger: "blur" },
          { min: 4, message: "用户名不能小于4位", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码必须填写", trigger: "blur" },
          { min: 6,max:50, message: "密码不能小于6位", trigger: "blur" },
        ],
      },
      // 加载
      loading:false,
      // 分配角色-显示数据-用户名-用户id
      roleVisible:false,
      username:'',
      userId:'',
      keyword:'',
      // 批量删除参数
      idList:[]
    };
  },
  mounted() {
    this.getPageList();
  },
  computed: {
    ...mapGetters("management", ["total", "pageList","checkedRoles","rolesList"]),
  },
  watch:{
    rolesList:{
      handler:function(newVal,oldVal){
        // console.log(this,'y=this')
        // console.log(newVal,'newVal')
      //  this.roles= newVal
       this.roles = newVal.map(item =>item.id)
      }
    },
    checkedRoles:{
      handler:function(newVal,oldVal){
        // console.log(this,'y=this')
        // console.log(newVal,'newVal')
        this.checkAllRoles = newVal.map(item => item.id )
      }
    }
    // pageList:{
    //   handler:function(newVal,oldVal){
    //     this.pageList = newVal
    //   }
    // }
  },
  methods: {
    // 获取用户管理列表
    async getPageList(page = 1) {
     try {
       this.current = page
       this.loading = true
      // console.log(page,'page',limit,'limit')
     await  this.$store.dispatch("management/getPageList", {page:this.current,limit:this.pageSize});
     this.loading = false
     } catch (error) {
       Message.error('获取列表数据失败')
     }
    },
    // 页数变化触发的函数
    handleSizeChange(size){
      // console.log(e,'e')
      this.pageSize = size
      this.getPageList()
    },
    // 点击添加按钮
    showDialog() {
      // 动态数据为布尔值true显示对话框
      this.dialogFormVisible = true;
      // 将数据进行清空不然会拿着之前编辑的数据发请求
      this.userControl = {
        nickName: "",
        password: "",
        username: "",
      }
      // // 将表单验证的错误信息进行清空
      this.$refs.userControlForm?.clearValidate()
    },
    // 点击编辑按钮
    showEditDialog(row){
      // 进行整体校验

      this.dialogFormVisible = true;
      // 回显数据-使用扩展运算操作新的对象数据
      this.userControl = { ...row };
    },
    // 点击确定按钮发请求
    async addUserControl() {
      //整体校验
      try {
        const valid = await this.$refs.userControlForm?.validate();
        if (valid) {
          // 整理数据
          // const token =localStorage.getItem('token_key')
          const userControl = this.userControl;
          // console.log(userControl, "usercomtrol");
          // 发请求
          // 成功干啥
          if (userControl.id) {
            // 修改管理用户
            await this.$store.dispatch(
              "management/reqUpdateLeader",
              userControl
            );
            Message.success("修改用户成功");
            this.getPageList();
          } else {
            // 新增管理用户
            await this.$store.dispatch("management/reqAddLeader",userControl);
            Message.success("新增管理用户成功");
            this.getPageList();
          }
        } else {
          Message.error("校验失败");
        }
        // 消息盒子关闭
        this.dialogFormVisible = false;
      } catch (error) {
        // 失败干啥
        // console.log(error.message);
         Message.error('请求失败')
      }
    },
    // 分配角色的函数
   showDispatchRole(row){
    // console.log(row.id,'row.id')
       // 设置角色的id
       this.userId = row.id
      // 消息盒子展示
      this.roleVisible = true
      // 设置角色的用户名
      this.username = row.username
      // console.log(this.userId,'useridjflgkjf')
      // 根据id发请求获取checkbox数据进行展示
      this.$store.dispatch('management/reqUserGetRole',row.id)
      // console/console.log( rolesList,' rolesList');
    },
    // 全选或者全不选的函数
     handleCheckAllChange(val) {
      // val为true全选 false全不选
      // 选中数组当中有内容为相等关系
      // console.log(val,'val')
      // console.log(this.checkAllRoles,'this.checkAllRoles')
       this.checkAllRoles = val ? this.roles : [];
      // 横线不显示
        this.isIndeterminate = false;
    },
     // 选中的角色对象的变化的函数
     handleCheckedRolesChange(value) {
        console.log(value)
        // 计算选中的数量
        let checkedCount = value.length;
        // 全选等于所有对象的数组的长度
        this.checkAll = checkedCount === this.roles.length;
        // 逻辑与运算遇到false就不向后执行显示横线
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
    },
     // 点击保存给用户设置角色
    async setRoles(){
       try {
         // 整理数据
         let  userId= this.userId 
        // roleId:选中的字符串的组合
       let  roleId = this.checkAllRoles.join(',')
        // console.log(this.userId,'11111111111')
        // console.log(roleId,'222222222222222222')
        //发请求
        await this.$store.dispatch("management/reqUserDispatchRole",{userId:userId,roleId:roleId});
        // 刷新页面
        Message.success("设置角色成功");
        // 获取页面数据
        this.getPageList();
        // 关闭消息盒子
        this.roleVisible = false
       } catch (error) {
        Message.error('请求设置角色失败')
       }
    },
    // 点击删除用户
    async removeOneUser(row){
    console.log(row.id,'row')
      try {
        await this.$store.dispatch('management/reqDeleteLeader',row.id)
        Message.success('删除用户成功')
        this.getPageList()
      } catch (error) {
        Message.error('请求删除失败')
      }
    },
    // 选中数据变化触发的事件
    handleSelectionChange(val){
      console.log(val)
      this.idList = val
    },
    // 删除多个用户
    async  removeAllUser(){
    try{
      const idList = this.idList
      await this.$store.dispatch('management/reqDeleteUserList',idList) 
      Message.success('批量删除成功')
      this.getPageList()
      } catch (error) {
        Message.error('请求批量删除失败')
      }
    },
    // 查询用户
    async searchUser(){
      try {
        await this.$store.dispatch('management/getPageList',{page:this.current,limit:this.pageSize,username:this.keyword})
      } catch (error) {
        Message.error('请求搜素数据失败')
      }
    },
    // 清空数据
    async clear(){
      try {
        this.keyword = ''
        await this.$store.dispatch('management/getPageList',{page:this.current,limit:this.pageSize,username:this.keyword})
      } catch (error) {
        Message.error('清空数据失败')
      }
    }


  }
};
</script>

<style scoped></style>
